import { Injectable } from '@nestjs/common';
import { PictureDto } from './dto/picture.dto';
import { PaginationDto } from 'src/common/dto/pagination.dto';
import { Picture } from './entities/picture.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { getPagination } from 'src/utils';
import { encryptFileMD5 } from 'src/utils/cryptogram.util';
import * as fs from 'node:fs';
import { uploadStaticSrc } from 'src/config/upload.config';

@Injectable()
export class PictureService {
  constructor(
    @InjectRepository(Picture)
    private readonly pictureRepository: Repository<Picture>,
  ) {}

  async getOneBySign(sign: string) {
    return await this.pictureRepository.findOne({
      where: { sign },
    });
  }

  async create(pictureDto: PictureDto) {
    return await this.pictureRepository.save(pictureDto);
  }
  async upload(file) {
    console.log('🚀 ~ PictureService ~ upload ~ file:', file);
    const { buffer } = file;
    const currentSign = encryptFileMD5(buffer);
    const hasPicture = await this.getOneBySign(currentSign);
    if (hasPicture) {
      return {
        src: hasPicture.src,
        sign: currentSign,
      };
    }

    const arr = file.originalname.split('.');
    const fileType = arr[arr.length - 1];
    const fileName = `${currentSign}.${fileType}`;
    fs.writeFileSync(`./upload/${fileName}`, buffer);

    const src = uploadStaticSrc + fileName;
    this.create({ src, sign: currentSign });
    return { src, sign: currentSign };
  }

  async findAll(paginationDto: PaginationDto) {
    const { page = 1, pageSize = 10 } = paginationDto;
    const getList = await this.pictureRepository
      .createQueryBuilder('picture')
      .where({ isDelete: false })
      .select(['picture.src', 'picture.sign'])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    const [list, total] = getList;
    const pagination = getPagination(page, pageSize, total);
    return {
      list,
      pagination,
    };
  }
}
